package com.argrace.smart.activity.devicerelation;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.R;
import com.argrace.smart.activity.QingJingListActivity;
import com.argrace.smart.base.BaseActivity;
import com.argrace.smart.base.ConstantConfigure;
import com.argrace.smart.entity.Key_ValueEntity;
import com.argrace.smart.entity.MineZigBeeDeviceListEntity;
import com.argrace.smart.glide.GliderImageLoaderUtil;
import com.argrace.smart.model.LocalDb_RelationDeviceTable;
import com.argrace.smart.ui.DrawableSwitch;
import com.argrace.smart.util.AlinkHttpUtil;
import com.zhouyou.view.seekbar.SignSeekBar;

import org.litepal.crud.DataSupport;

import java.util.HashMap;
import java.util.List;

/**
 * Created by argrace_dev_1 on 2018/3/5.
 */

public class DeviceRelation_XinFengKongZhiQiActivity extends BaseActivity {
    private ImageView img;
    private SignSeekBar fengsu;
    private DrawableSwitch kaiguan;
    MineZigBeeDeviceListEntity bean;
    private int type = ConstantConfigure.TYPE_CONTROL;
    //此处开始修改为关联设备增加的属性
    String uuid, model;
    LinearLayout relationdevice_ll;
    TextView relationdevice_text;
    private int qingJingTable_id = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_devicecontrol_xinfengji);
        init();
    }

    private void init() {
        bean = (MineZigBeeDeviceListEntity) getIntent().getSerializableExtra("deviceinfo");
        uuid = bean.getUuid();
        model = bean.getModel();
        setView();
        setTitle(true, false, "添加关联");
        showRight(true, R.mipmap.head_title_tick);
        //点击右上角保存此时设备状态与关联场景
        setLeftandRightClickListeners(null, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });
        getDeviceDetailInfo();
    }

    private void save() {
        LocalDb_RelationDeviceTable relationDeviceTable = new LocalDb_RelationDeviceTable();
        relationDeviceTable.setUuid(uuid);
        relationDeviceTable.setModel(model);
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        sb.append("\"WindSpeed\" :");
        Key_ValueEntity entity_dianliang = new Key_ValueEntity();
        //sds控制台数值为2、3、4对应progress0、1、2
        entity_dianliang.setValue(String.valueOf(fengsu.getProgress() + 2));
        sb.append(entity_dianliang.toString());
        sb.append(",");
        if (kaiguan.isSwitchOn()) {
            sb.append("\"Switch\" :");
            Key_ValueEntity entity = new Key_ValueEntity();
            entity.setValue("1");
            sb.append(entity.toString());
            sb.append(",");
        } else {
            sb.append("\"Switch\" :");
            Key_ValueEntity entity = new Key_ValueEntity();
            entity.setValue("0");
            sb.append(entity.toString());
            sb.append(",");
        }
        sb.append("}");
        relationDeviceTable.setTrigger_condition(sb.toString());
        relationDeviceTable.setQingJingTable_id(qingJingTable_id);
        List<LocalDb_RelationDeviceTable> lists = DataSupport.where("uuid = ?", uuid).find(LocalDb_RelationDeviceTable.class);
        boolean is_same = false;
        int table_id = 0;
        if (lists != null && lists.size() > 0) {
            for (int i = 0; i < lists.size(); i++) {
                if (lists.get(i).getTrigger_condition() != null && lists.get(i).getTrigger_condition().equals(relationDeviceTable.getTrigger_condition())) {
                    is_same = true;
                    table_id = lists.get(i).getId();
                }
            }
        }
        //如果相等则updata
        if (is_same) {
            relationDeviceTable.update(table_id);
        } else {
            relationDeviceTable.save();
        }
        finish();
        toastActBtm("保存成功");
    }

    private void setView() {
        img = (ImageView) findViewById(R.id.activity_devicecontrol_img);
        fengsu = (SignSeekBar) findViewById(R.id.activity_devicecontrol_xinfengji_fengsu);
        kaiguan = (DrawableSwitch) findViewById(R.id.activity_devicecontrol_xinfengji_kaiguan);
        //modify for relationdevice start
        relationdevice_ll = (LinearLayout) findViewById(R.id.activity_devicecontrol_baojing_relationdevice_ll);
        relationdevice_text = (TextView) findViewById(R.id.activity_devicecontrol_baojing_relationdevice_text);
        relationdevice_ll.setVisibility(View.VISIBLE);
        relationdevice_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DeviceRelation_XinFengKongZhiQiActivity.this, QingJingListActivity.class);
                startActivityForResult(intent, ConstantConfigure.DEFAULT_ZERO);
            }
        });
        //modify for relationdevice end
        String imgurl = ConstantConfigure.IMGURL_XINFENGKONGZHIQI_00281E15;
        if (imgurl != null) {
            GliderImageLoaderUtil.load(this, imgurl, img);
        }

        fengsu.getConfigBuilder()
                .min(0)
                .max(2)
                .progress(1)
                .sectionCount(2)
                .thumbColor(ContextCompat.getColor(DeviceRelation_XinFengKongZhiQiActivity.this, R.color.elune_blue))
                .sectionTextColor(ContextCompat.getColor(DeviceRelation_XinFengKongZhiQiActivity.this, R.color.colorPrimary))
                .sectionTextSize(16)
                .sectionTextPosition(SignSeekBar.TextPosition.BELOW_SECTION_MARK)
                .build();
        kaiguan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int state = kaiguan.isSwitchOn() ? 0 : 1;
                kaiguan.setSwitchOn(!kaiguan.isSwitchOn());
                kaiguan.invalidate();
            }
        });


    }

    //查询设备最新状态
    private void getDeviceDetailInfo() {
        String method = "mtop.openalink.app.core.device.get.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", bean.getUuid());
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                if (transitoryResponse == null || transitoryResponse.data == null) {
                    return;
                }
                Log.i("info", "子设备最新状态成功" + transitoryResponse.data);
                JSONObject obj = JSON.parseObject(transitoryResponse.data.toString());
                fillData(obj, obj.getString("uuid"));
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "子设备最新状态失败" + aError.getMsg() + aError.getCode());
            }
        });
    }


    private void fillData(JSONObject obj, String uuid) {
        if (uuid == null || !uuid.equals(bean.getUuid())) {
            return;
        }
        Key_ValueEntity bean_fengsu = JSON.parseObject(obj.getString("WindSpeed"), Key_ValueEntity.class);
        Key_ValueEntity bean_kaiguan = JSON.parseObject(obj.getString("Switch"), Key_ValueEntity.class);
        fengsu.setProgress(Long.parseLong(bean_fengsu.getValue()) - 2);
        if (bean_kaiguan != null && bean_kaiguan.getValue() != null && bean_kaiguan.getValue().equals("1")) {
            kaiguan.setSwitchOn(true);
        } else {
            kaiguan.setSwitchOn(false);
        }
        kaiguan.invalidate();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String name = data.getStringExtra("name");
            qingJingTable_id = data.getIntExtra("id", 0);
            relationdevice_text.setText(name);
        }
    }
}


